# -*- coding: utf-8 -*-
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from app_accounts.models import *
from app_TuringClass.models import *
from app_OnlineExam.models import *
from django.core.exceptions import *
from django import forms
#send e-mail
from django.core.mail import send_mail
# 调用自行编写的lib库
from app_TuringClass.lib_appTuringClass import *
from app_TuringClass.turning_class import *


##考试模块
@csrf_exempt
def ShowQuestion(request):
	print request
	ID= request.POST['form']
	examid = ID.split('_',1)[1]
	courseid = ID.split('_',1)[0]
	print ID
	questions = SingleProblem.objects.filter(CourseID = courseid,ExamID = examid).order_by("SingleProblemID")
	print questions
	Questions =[]
	for question in questions:
		Question ={}
		Question['QuestionTitle'] = question.SingleTitle
		Question['QuestionID'] = question.CourseID+'_'+question.ExamID+'_'+str(question.SingleProblemID)
		Question['OptionA'] = question.OptionA
		Question['OptionB'] = question.OptionB
		Question['OptionC'] = question.OptionC
		Question['OptionD'] = question.OptionD
		Questions.append(Question)
	
	print ID
	context ={
			'questions':Questions,
	}
	return render(request, 'OnlineTestDemo.html', context)

@csrf_exempt
def AnswerQuestion(request):
	i = 0
	score = 0
	l = request.POST['length']
	answer = request.POST['answer']
	ID = request.POST['examid']
	print ID[0]
	courseid = ID.split('_',2)[0]
	courseid = courseid.split('"',1)[1]
	examid = ID.split('_',2)[1]
	print courseid
	print examid
	if request.POST:
		print request.POST
		try:
			for i in range(0,int(l)):
				question = SingleProblem.objects.get(CourseID =courseid ,ExamID =examid,SingleProblemID = i+1)
				print question
				print answer [4*i+2]
				if answer[4*i+2] == question.SingleAnswer:
					score = score + 4 	
			return HttpResponse(score)
		except Exception, e:
			print e
			raise Http404				
		
	return HttpResponse('Whoops!')

@csrf_exempt
def Exam(request):
	exams = SingleProblem.objects.all()
	Exams = []
	string  = 'begin'
	for exam in exams:
		Exam = {}
		if exam.ExamID != string :
			Exam['examid'] = exam.CourseID+'_'+exam.ExamID
			Exams.append(Exam)
			string = exam.ExamID
	print Exams
	context ={
			'Exams':Exams,
	}
	return render (request,'exam.html',context)


##出题
class ExamPaperForm(forms.Form):
	coursename = forms.CharField(required=True,
								max_length =20,
								error_messages={'required':'课程名称不能为空','max_length':'课程名称最多20位'})
	examname = forms.CharField(required=True,
							max_length = 40,
							error_messages={'required':'试卷名称不能为空','max_length':'试卷名称最多40位'})

@csrf_exempt
def AddExamPaper(request):
	if request.POST:
		objPost = ExamPaperForm(request.POST)
		ret = objPost.is_valid()
		if ret:
			coursename = objPost.cleaned_data['coursename']
			examname = objPost.cleaned_data['examname']
			ExamPaperInfo(CourseID=coursename,ExamID=examname,ExamTime=90,TotalScore=100,TeacherID=1).save()
			request.session['ExamID'] = examname
			return HttpResponseRedirect('/OnlineExam/AddSingleProblem/')
		else:
			pass
		return render(request,'AddExamPaper.html',{'obj1':objPost})
	else:
			objGet = ExamPaperForm()
			return render(request,'AddExamPaper.html',{'obj1':objGet})

class SingleProblemForm(forms.Form):
	singletitle = forms.CharField(required=True,
								widget = forms.Textarea,
								max_length = 2000,
								error_messages={'required':'题目不能为空','max_length':'题目长度最多2000位'})
	optionA = forms.CharField(required = True,
							max_length = 500,
							error_messages={'required':'选项不能为空','max_length':'选项长度最多500位'})
	optionB = forms.CharField(required = True,
							max_length = 500,
							error_messages={'required':'选项不能为空','max_length':'选项长度最多500位'})
	optionC = forms.CharField(required = True,
							max_length = 500,
							error_messages={'required':'选项不能为空','max_length':'选项长度最多500位'})
	optionD = forms.CharField(required = True,
							max_length = 500,
							error_messages={'required':'选项不能为空','max_length':'选项长度最多500位'})
	SingleChoice = (('A', 'A'), ('B', 'B'),('C','C'),('D','D'))
	singleanswer = forms.ChoiceField(required = True,
							choices = SingleChoice,
							error_messages={'required':'答案不能为空'})

@csrf_exempt
def AddSingleProblem(request):
	if request.POST:
		objPost = SingleProblemForm(request.POST)
		ret = objPost.is_valid()
		if ret:
			print request.POST
			singletitle = objPost.cleaned_data['singletitle']
			optionA = objPost.cleaned_data['optionA']
			optionB = objPost.cleaned_data['optionB']
			optionC = objPost.cleaned_data['optionC']
			optionD = objPost.cleaned_data['optionD']
			singleanswer = objPost.cleaned_data['singleanswer']
			SingleProblem(PrimaryID = len(SingleProblem.objects.all())+1,SingleProblemID = len(SingleProblem.objects.filter(ExamID = request.session['ExamID']))+ 1,CourseID = ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).CourseID,ExamID = request.session['ExamID'],SingleTitle = singletitle,OptionA = optionA,OptionB = optionB,OptionC = optionC,OptionD = optionD,SingleAnswer = singleanswer).save()
			if request.POST['submit'] == u'下一题':
				return HttpResponseRedirect('/OnlineExam/AddSingleProblem/')
			else:
				return HttpResponseRedirect('/OnlineExam/ShowExamPaper/')
		else:
			return render(request,'AddSingleProblem.html',{'obj1':objPost})
	else:
		objGet = SingleProblemForm()
		return render(request,'AddSingleProblem.html',{'obj1':objGet})

def ShowExamPaper(request):
	questions = SingleProblem.objects.filter(ExamID = request.session['ExamID']).order_by("SingleProblemID")
	Questions =[]
	for question in questions:
		Question = {}
		Question['QuestionTitle'] = question.SingleTitle
		Question['OptionA'] = question.OptionA
		Question['OptionB'] = question.OptionB
		Question['OptionC'] = question.OptionC
		Question['OptionD'] = question.OptionD
		Question['Answer'] = question.SingleAnswer
		Questions.append(Question)
	context ={
			'CourseID':ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).CourseID,
			'ExamID':request.session['ExamID'],
			'questions':Questions,
	}
	return  render_to_response('ShowExamPaper.html',context)
